package com.keda.controller;


import com.keda.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 1. 接收参数 用户名、密码、用户提交验证码、后端生成的验证码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String verifyCode = request.getParameter("verifyCode");

        // 2. 调用Service登录
        UserService userService = new UserService();
        String message = userService.login(username, password, verifyCode,
                request.getSession());

        // 3. 返回结果
        if ("登录成功！".equals(message)) { // 成功跳转到登录成功页面
            request.getRequestDispatcher("login-success.jsp").forward(request, response);
            return;
        }

        // 失败，跳转到登录页面
        request.getSession().setAttribute("error", message);
        // 失败，不能直接跳转到login.jsp，原因是login.jsp中有其他的数据，因此使用重定向功能
        request.getRequestDispatcher("login.jsp").forward(request, response);

    }
}
